package com.zhugang.week07;

/**
 * @program algorithms
 * @description: flatten
 * @author: chanzhugang
 * @create: 2022/07/22 23:15
 */
public class Flatten {

    /**
     * 114 二叉树展开为链表
     *
     * @param root
     */

    private TreeNode dummyHead = new TreeNode();
    private TreeNode tail = dummyHead;

    public void flatten(TreeNode root) {
        // 按先序遍历顺序展开
        // 虚拟头节点、尾插
        preorder(root);

    }

    private void preorder(TreeNode root) {
        // 先序遍历
        if (root == null) {
            return;
        }
        // 先序处理逻辑
        // 提前记录左右子节点
        TreeNode left = root.left;
        TreeNode right = root.right;

        tail.right = root;
        tail = root;
        root.left = null;

        // 左子树
        preorder(left);
        // 右子树
        preorder(right);
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}